import json
import time
import requests
import datetime

from prettytable import PrettyTable

from email_test import send_email, send_error_email

login_url = 'https://kyfw.12306.cn/otn/resources/login.html'
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3664.3 Safari/537.36'
}
res = requests.get(login_url, headers=headers)
cookies = res.cookies
print('程序初始化完成...')
print('-------------------------------------')

cf = input('请输入出发地：')
dz = input('请输入目的地：')
sj = input('请输入时间：')
url = 'https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT' % (sj, cf, dz)
headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'kyfw.12306.cn',
    'If-Modified-Since': '0',
    'Referer': 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=%E5%8C%97%E4%BA%AC,BJP&ts=%E8%A1%A1%E6%B0%B4,HSP&date=2019-10-01&flag=N,N,Y',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}
train_num = 0
s = requests.get(url, headers=headers,cookies=cookies)
data_json = json.loads(s.text)
train_num = len(data_json['data']['result'])
print('当前检测到%s班列车...' % len(data_json['data']['result']))
time.sleep(1)
print('持续刷新中...')
time.sleep(1)
while True:
    s = requests.get(url, headers=headers,cookies=cookies)
    data_json = json.loads(s.text)
    if len(data_json['data']['result']) > train_num:
        send_email()
        print('新开车了哦！！赶紧去抢吧')
        break
    else:
        now_time = datetime.datetime.now()
        now_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
        print('当前时间:%s' % now_time)
        print('再等等吧！！别着急')
    time.sleep(60)
